using System;
using System.Collections.Generic;
using System.Text;

namespace Kopain
{

    /// <summary>This is a helper class to export the KOP format to another format.
    /// </summary>
    internal class Export
    {

        /// <summary>This method exports the whole tree to a file/directory structure readable by anyone.
        /// </summary>
        /// <param name="path">The path where the Root is placed.</param>
        /// <param name="filename">The directoryname of the root.</param>
        /// <param name="notes">The notes directly under the root.</param>
        /// <example>
        ///     Export.ExportSavefile( 
        ///         System.IO.Path.GetDirectoryName( dlg.FileName ), 
        ///         System.IO.Path.GetFileName( dlg.FileName ), 
        ///         _saveFile.NoteRoot.Note );
        /// </example>
        internal static void ExportSavefile( string path, string filename, NoteType[] notes )
        {
            //  Return directly if we don't have any Note.
            //  Filtering when to stop recursive calls can be done by the caller or callee, I chose callee here.
            if( null == notes ) { return; }

            //  Create the path to store the Notes.
            //
            string newPath = string.Format( "{0}\\{1}", path, filename );
            System.IO.Directory.CreateDirectory( newPath );

            //  Loop through the Notes and create one file per each.
            //  After the file is created, call this method recursively with the subnotes.
            foreach( NoteType n in notes )
            {
                Save( newPath, n );
                ExportSavefile( newPath, n.title, n.Note );
            }
        }


        /// <summary>This method saves a Note as a file.  It figures out if the Note's data is stored
        /// inline or in a subfile and reacts accordingly.
        /// The functionality here is quite similar to the one in the Info dialogue where the user can
        /// convert an inline note to a subfile and vice verse.
        /// The path is sent along to the method and the name of the file is created by the Note's title.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="note"></param>
        private static void Save( string path, NoteType note )
        {
            if( string.IsNullOrEmpty( note.file ) )
            {
                //  File is empty means data is stored inline.  So create a file and fill it with data.
                //
                System.IO.File.WriteAllText( CreateUnique( path, note.title ), note.Data );
            }
            else
            {
                //  No data means the data is stored in a file.  So copy the file to the target dir.
                //
                System.IO.File.Copy( note.FileWithPath( note.Root ), CreateUnique( path, note.title ) );
            }
        }


        /// <summary>This method creates a unique file name.
        /// It first tries the 'title' but if that doesn't work it appends a number.  If that doesn't work it increases the number
        /// and tries again.
        /// With a ridiculous high number it fails with an exception.  With a ridiculous high number...
        /// </summary>
        /// <param name="path">The path to store the file.  No trailing backslash.</param>
        /// <param name="title">The title of the file.  If it is occupied the title is changed.</param>
        /// <returns>A path wth filename that is not used.</returns>
        private static string CreateUnique( string path, string title )
        {
            string filename = string.Format( "{0}\\{1}.rtf", path, title );
            if( !System.IO.File.Exists( filename ) )
            {
                return filename;
            }
            else
            {
                for( int i = 1 ; i < 10000 ; i++ )
                {
                    string filenameWithNumericSuffix = string.Format( "{0}\\{1}-{2}.rtf", path, title, i );
                    if( !System.IO.File.Exists( filenameWithNumericSuffix ) ){
                        return filenameWithNumericSuffix;
                    }
                }
                throw new Exception.TooManySimilarTitlesToExport( filename );
            }
        }

    }

}
